<?php
/**
 * 飞信机器人--事件插件--定时器
 * 功能： 每隔10秒激活一次
 * 作者： Kelvin
 * 联系： msn:shichangguo@msn.com, qq:191848423
*/
require_once('./plugins/inc/config.inc.php');
require_once('./plugins/inc/utils.inc.php');
require_once('./plugins/inc/db.inc.php');

$srvMobile = $argv[1];
$tick = $argv[2];	//机器人运行至今的秒数

// 定时抽奖模块

//每天晚上12点自动抽奖
$autoRaffleTime = "00";
$time = date('H');
if($time != $autoRaffleTime ) die();

//判断自动抽奖开关，是否打开
$db = new CDb($srvMobile);
$sql = "select * from fx_config where fx_config.key='AUTO_RAFFLE_ON'";
$rows = $db->fetchQueryAll($sql);
if( count($rows)==0 )die();
if($rows[0]['value'] == 0 )die(); // 自动抽奖关闭

//判断当天是否已经抽奖
$time = date('Y-m-d H');
$sql = "select * from fx_config where fx_config.key='AUTO_RAFFLE_REC'";	//抽奖记录
$rows = $db->fetchQueryAll($sql);
if( $time == $rows[0]['value'])die(); //当天已经抽奖

//获取抽奖事件ID
$sql = "select * from fx_config where fx_config.key='AUTO_RAFFLE_EVENT_ID'";	//抽奖记录
$rows = $db->fetchQueryAll($sql);
$eventID = $rows[0]['value'];

//获取抽奖数目
$sql = "select * from fx_config where fx_config.key='AUTO_RAFFLE_NUMBER'";	//抽奖数目
$rows = $db->fetchQueryAll($sql);
$number = $rows[0]['value'];

//当天未抽奖,抽奖并记录状态。从昨天记录中抽取
$lastDay =  date("Y-m-d",time()-24*60*60); 
$sql = "SELECT b.sid,b.mobile,b.nick_name,b.local_name,a.id,a.buddy_id,a.event_id,a.add_time,left(from_unixtime(a.add_time),10) as timestr  ";
$sql.=" FROM fx_participate a Inner Join fx_buddies b ON a.buddy_id = b.id where event_id={$eventID} and left(from_unixtime(a.add_time),10)='{$lastDay}' order by a.id desc";
//echo $sql."\n";
$rows = $db->fetchQueryAll($sql);
//print_r($rows);
$count = count($rows);
//随机,$number:个数
if( $count < $number )
{
	//'数量太少，全部中奖');
	$randArr = array();
	for($i=0; $i<$count; $i++)
	{
		$randArr[] = $i+1;
	}
}else
{
	$number = intval($number);
	$randArr = array();
	for($i=0; $i<$number; $i++)
	{	
		while($r = rand(1,$count))
		{
			if( !in_array($r, $randArr) )
			{
				$randArr[] = $r;
				break;
			}
		}
	}
}			
$retArr = array();
for($i=0; $i<count($randArr); $i++)
{
	$retArr[] = $rows[$randArr[$i]-1];
	$sql = "insert into fx_auto_raffle(event_id,buddy_id,raffle_time) values({$eventID},{$rows[$randArr[$i]-1]['buddy_id']},'{$lastDay}')";
	echo $sql."\n";
	$db->execute($sql);
}

// 记录已经抽取
$sql = "update fx_config set value='{$time}' where fx_config.key='AUTO_RAFFLE_REC'";
$db->execute($sql);
?>